Smallest subtree with all the deepest nodes [DFS]

Time: O(N); Space: O(H); medium

Given a binary tree rooted at root, the depth of each node is the shortest distance to the root.

A node is deepest if it has the largest depth possible among any node in the entire tree.

The subtree of a node is that node, plus the set of all descendants of that node.

Return the node with the largest depth such that it contains all the deepest nodes in its subtree.

Example 1:

Input: root = {TreeNode} [3,5,1,6,2,0,8,null,null,7,4]

Output: {TreeNode} [2,7,4]

Explanation:

  • We return the node with value 2, colored in yellow in the diagram.

  • The nodes colored in blue are the deepest nodes of the tree.

  • The input “[3, 5, 1, 6, 2, 0, 8, null, null, 7, 4]” is a serialization of the given tree.

  • The output “[2, 7, 4]” is a serialization of the subtree rooted at the node with value 2.

  • Both the input and output have TreeNode type.

Notes:

  • The number of nodes in the tree will be between 1 and 500.

  • The values of each node are unique.

[15]:
class TreeNode(object):
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

Auxiliary Tools¶

[16]:
from graphviz import Graph

class TreeTasks(object):
    def create_binary_tree(self, nums):
        root = None
        len_nums = len(nums)
        idx = 0
        res = self.insertLevelOrder(nums, root, idx, len_nums)
        return res

    def insertLevelOrder(self, nums, root, idx, len_nums):
        # Base case for recursion
        if idx < len_nums:
            temp = TreeNode(nums[idx])
            root = temp
            # insert left child
            root.left = self.insertLevelOrder(nums, root.left, 2 * idx + 1, len_nums)
            # insert right child
            root.right = self.insertLevelOrder(nums, root.right, 2 * idx + 2, len_nums)
        return root

    def visualize_tree(self, tree):
        def add_nodes_edges(tree, dot=None):
            # Create Graph (not Digraph) object
            if dot is None:
                dot = Graph()
                dot.node(name=str(tree), label=str(tree.val))
            # Add nodes
            if tree.left and tree.left.val != "#":
                dot.node(name=str(tree.left), label="."+str(tree.left.val))
                dot.edge(str(tree), str(tree.left))
                dot = add_nodes_edges(tree.left, dot=dot)
            if tree.right and tree.right.val != "#":
                dot.node(name=str(tree.right), label=str(tree.right.val)+".")
                dot.edge(str(tree), str(tree.right))
                dot = add_nodes_edges(tree.right, dot=dot)
            return dot
        # Add nodes recursively and create a list of edges
        dot = add_nodes_edges(tree)
        # Visualize the graph
        display(dot)
        return dot